package com.zrc.japktool.util;

import java.io.*;
import java.util.Locale;

public class CmdUtil {

    public static boolean isWinOS() {
        return System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win");
    }

    public static boolean isMacOS() {
        return System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("mac");
    }

    public static boolean isLinOS() {
        String os = System.getProperty("os.name").toLowerCase(Locale.ROOT);
        return os.contains("nix")|| os.contains("nux")|| os.contains("aix");
    }

    public static void exec(String cmd, TaskLog log) throws Exception {
        log.tip("执行终端命令: " + cmd);
        Process process = Runtime.getRuntime().exec(cmd);
        try (BufferedReader iReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); BufferedReader eReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"))) {
            String iLine;
            while ((iLine = iReader.readLine()) != null) {
                if (iLine.contains("error") || iLine.contains("failed")) {
                    log.error(iLine);
                } else {
                    log.info(iLine);
                }
            }

            String eLine;
            while ((eLine = eReader.readLine()) != null) {
                if (eLine.contains("error") || eLine.contains("failed")) {
                    log.error(eLine);
                } else {
                    log.info(eLine);
                }
            }
        }
        int exitCode = process.waitFor();
        if (exitCode == 0) {
            log.info("执行终端命令: 执行完成,退出码[" + exitCode + "]");
        } else {
            log.error("执行终端命令: 执行失败,退出码[" + exitCode + "]");
            //throw new RuntimeException("执行终端命令: 执行失败,退出码[" + exitCode + "]");
        }
    }

    public static void main(String[] args) throws Exception {
        if (CmdUtil.isWinOS()){
            String cmd = new File(CmdUtil.class.getResource("/windows/adb.exe").toURI()).getPath()+" --version";
            CmdUtil.exec(cmd,TaskLog.newTaskLog());
        }
    }
}

